package ren.kane.phoenix.util.reflect;

import java.lang.reflect.Field;

/**
 * @author renrk(1275) on 2019-08-14 9:33 AM
 **/
public class FieldTest {

    private static void testGetDeclaredField() {
        try {
            Class<?> clazz = Person4.class;
            Object person = clazz.newInstance();
            Field fName = clazz.getDeclaredField("name");
            Field fAge = clazz.getDeclaredField("age");
            Field fGender = clazz.getDeclaredField("gender");

            fName.set(person, "Tom");
            fAge.set(person, 30);
            fGender.setAccessible(true);
            fGender.set(person, Gender.MALE);
            System.out.printf("%-30s: person=%s\n", "getDeclaredField()", person);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void testGetField() {
        try {
            Class<?> clazz = Person4.class;
            Object person = clazz.newInstance();
            Field fName = clazz.getDeclaredField("name");
            fName.set(person, "Tom");
            System.out.printf("%-30s: person=%s\n", "getField()", person);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        testGetDeclaredField();
        testGetField();
    }
}

class Person4 {

    public String name;
    protected int age;
    private Gender gender;

    public Person4() {
        this("unknown", 0, Gender.FEMALE);
    }

    public Person4(String name, int age, Gender gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "(" + name + ", " + age + ", " + gender + ")";
    }
}